//
//  Utils.swift
//  股票框架
//
//  Created by 李小骥 on 2017/9/28.
//  Copyright © 2017年 李小骥. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import RxSwift
import RxCocoa
import CryptoSwift
import Photos

class Utils: NSObject {
    class func md5String(str:String) -> String{
        let cStr = str.cString(using: String.Encoding.utf8);
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)
        CC_MD5(cStr!,(CC_LONG)(strlen(cStr!)), buffer)
        let md5String = NSMutableString();
        for i in 0 ..< 16{
            md5String.appendFormat("%02x", buffer[i])
        }
        free(buffer)
        return md5String as String
    }
    class func kRGBColorFromHex(rgbValue: Int) -> (UIColor) {
        return UIColor(red: ((CGFloat)((rgbValue & 0xFF0000) >> 16)) / 255.0,green: ((CGFloat)((rgbValue & 0xFF00) >> 8)) / 255.0,blue: ((CGFloat)(rgbValue & 0xFF)) / 255.0,alpha: 1.0)
         }
    class func adjustLabelWidth(text:String,font:UIFont,height:CGFloat) -> CGFloat {
        
        let statusLabelText: NSString = text as NSString
        
        let size = CGSize(width: 900, height: height)
        
        let dic = NSDictionary(object: font, forKey: NSAttributedStringKey.font as NSCopying)
        
        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedStringKey : Any], context: nil).size
        
        return strSize.width
        
    }
//    所有的网络请求都有一个逃逸闭包参数，它代表传递请求结果给请求的后续操作，因为网络请求和后续操作通常不再1个线程里面所以逃逸闭包，它的形参表列是网络请求传回给接受者的参数，它的实现在接受者内部定义，网络请求结束时调用闭包参数
    class func AlamofireAsynchronousPOSTPhoneNumber(pNumber:String,callBack:@escaping (Bool)->Void) {
        let url = URL(string:"http://ad.cctvzxjy.com/User/send")
//        一定显示声明参数格式是框架提供的格式，否则自动转换格式会使字典为空
        let parameters: Parameters = [
            "mobile":"\(pNumber)"
        ]
        
//        url：URL 格式的网址；method：post 或者 get 方式等；parameters：请求参数的字典；encoding：以网址方式请求用URLEncoding.default；header：请求头，本次请求没有头部内容
        Alamofire.request(url!, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).validate(statusCode: 200..<300).responseJSON { (response)  in
            switch response.result{
            case .success:
                if let value = response.result.value {
                    let json = JSON(value)
                    let code = json["code"].intValue
                    let data = json["data"].stringValue
                    let message = json["message"].stringValue
                    let status = json["status"].intValue
                    if(code == 40000){
//                        登录成功：初始化 loginmodel 类型的结构体，保存这些临时参数，返回元组 （true，结构体）
                        vCode = RequestVerificationCode(code: code, data: data, message: message, status: status)
//                        print("VCODE:\(vCode!)")
                        callBack(true)
                    }
                }
            case .failure(let error):
//                print(error)
                callBack(false)
            }
            
        }
    }
    class func AlamofireAsynchronousGETSearchZixuanguData(code:String,callBack:@escaping ([SearchZixuanguData]?)->Void) {
        let url = URL(string:"http://ad.cctvzxjy.com/Index/search/")//http://ad.cctvzxjy.com/Index/search/code/000301
        //        一定显示声明参数格式是框架提供的格式，否则自动转换格式会使字典为空
        
        let parameters : Parameters = [
            "code":code
        ]
        
        //        url：URL 格式的网址；method：post 或者 get 方式等；parameters：请求参数的字典；encoding：以网址方式请求用URLEncoding.default；header：请求头，本次请求没有头部内容
        Alamofire.request(url!, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).validate(statusCode: 200..<300).responseJSON { (response)  in
            switch response.result{
            case .success:
                if let value = response.result.value {
                    let json = JSON(value)
                    let code = json["code"].stringValue
                    if(code == "40000"){
                    let dataDictionaryArray = json["data"].arrayValue
                    let message = json["message"].stringValue
                    var dataArray:[SearchZixuanguData] = []
                    let resultsCount = (10 < dataDictionaryArray.count) ? 10:dataDictionaryArray.count
                    for i in 0..<resultsCount{
                        let data = SearchZixuanguData(stockType: dataDictionaryArray[i]["stockType"].stringValue, market: dataDictionaryArray[i]["market"].stringValue, name: dataDictionaryArray[i]["name"].stringValue, state: dataDictionaryArray[i]["state"].intValue, currcapital: dataDictionaryArray[i]["currcapital"].stringValue, profit_four: dataDictionaryArray[i]["profit_four"].stringValue, code: dataDictionaryArray[i]["code"].stringValue, totalcapital: dataDictionaryArray[i]["totalcapital"].stringValue, mgjzc: dataDictionaryArray[i]["mgjzc"].stringValue, pinyin: dataDictionaryArray[i]["pinyin"].stringValue, listing_date: dataDictionaryArray[i]["listing_date"].stringValue, ct: dataDictionaryArray[i]["ct"].stringValue)
                        dataArray.append(data)
                    }
//                        print(json)
                    //                    print(code)
                    
                        //                        登录成功：初始化 loginmodel 类型的结构体，保存这些临时参数，返回元组 （true，结构体）
                        //                                               print("TimeChartResult:\(timeChartResult!)")
                        callBack(dataArray)
                        //                        NotificationCenter.default.rx.notification(Notification.Name(rawValue: "stockDataGotten"), object: timeChartResult! as AnyObject)
                        //                        print(code)
                        
                        
                    }else{
                        let emptyArray:[SearchZixuanguData] = []
                        callBack(emptyArray)
                    }
                }
                
            case .failure(let error):
                print("error")
                
            }
            
        }
        
    }
//    class func synchronousPostPhoneNumber(pNumber:String) {
//
//        // 1、创建URL对象；
//        let url:URL! = URL(string:"http://ad.cctvzxjy.com/User/send")
//
//        // 2、创建Request对象
//        // url: 请求路径
//        // cachePolicy: 缓存协议
//        // timeoutInterval: 网络请求超时时间(单位：秒)
//        var urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
//
//        // 3、设置请求方式为POST，默认是GET
//        urlRequest.httpMethod = "POST"
//
//        // 4、设置参数
//        let str:String = "mobile=\(pNumber)"
//        let data:Data = str.data(using: .utf8, allowLossyConversion: true)!
//        urlRequest.httpBody = data;
//
//        // 5、响应对象
//        var response:URLResponse?
//
//        // 6、发出请求
//        do {
//
//            let received =  try NSURLConnection.sendSynchronousRequest(urlRequest, returning: &response)
//            let dic = try JSONSerialization.jsonObject(with: received, options: JSONSerialization.ReadingOptions.allowFragments)
//            print(dic)
////            let requestVerificationResult = requestVerificationCode(dictionary: dic as! Dictionary<String, Any>)
////            print(requestVerificationResult)
//
//
//
//            //let jsonStr = String(data: received, encoding:String.Encoding.utf8);
//            //print(jsonStr)
//
//        } catch let error{
//            print(error.localizedDescription);
//        }
//
//    }
    //    所有的网络请求都有一个逃逸闭包参数，它代表传递请求结果给请求的后续操作，因为网络请求和后续操作通常不再1个线程里面所以逃逸闭包，它的形参表列是网络请求传回给接受者的参数，它的实现在接受者内部定义，网络请求结束时调用闭包参数
    class func AlamofireAsynchronousPOSTPhoneNumber(pNumber:String,verificationCode:String,callBack:@escaping (Bool)->Void) {
        let url = URL(string:"http://ad.cctvzxjy.com/User/login")
        //        一定显示声明参数格式是框架提供的格式，否则自动转换格式会使字典为空
        let parameters: Parameters = [
            "mobile":"\(pNumber)",
            "code":"\(verificationCode)",
            "app":"iOS"
        ]
        
       Alamofire.request(url!, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).validate(statusCode: 200..<300).responseJSON { (response) in
        switch response.result{
        case .success:
            if let value = response.result.value {
                let json = JSON(value)
                let status = json["status"].stringValue
                let data = json["data"]
                let code = json["code"].stringValue
                let message = json["message"].stringValue
                let qq = data["qq"].stringValue
                let user_rank = data["user_rank"].stringValue
                let uid = data["id"].stringValue
                let image = data["image"].stringValue
                let token = data["token"].stringValue
                let experience = data["experience"].stringValue
                let birthday = data["birthday"].stringValue
                let area = data["area"].stringValue
                let user_name = data["user_name"].stringValue
                let sex = data["sex"].stringValue
                print(json)
//                print("code:\(code),uid:\(uid),token:\(token),image:\(image),message:\(message),status:\(status)")
                if(code=="40000"){
                    //                    登录成功：初始化 loginmodel 类型的结构体，保存这些临时参数，返回元组 （true，结构体）
                    lCode = RequestLoginCode(status: status, code: code, message: message, qq: qq, user_rank: user_rank, userID: uid, imageUrl: image, token: token, experience: experience, birthday: birthday, area: area, user_name: user_name, sex: sex,phoneNumber:pNumber)
//                    saveAccount(userInfo: lCode!)
//                    初次申请到头像，直接需要保存，callback 需要调整
                    
                    

                    print("LCODE:\(lCode!)")
                   callBack(true)
                }
             
            }
            
        case .failure(let error):
            print(error)
           callBack(false)
        }
        }
    }
//    tokens
    class func AlamofireAsynchronousGETUserInfo(callBack:@escaping (UIImage)->Void) {
        let url = URL(string:"http://ad.cctvzxjy.com/User/getUserInfo")
        let date = Date()
        let time = date.toString("ddmmHH")
        let uuid = (lCode?.userID)!
        let token = (lCode?.token)!
        let combinedString = uuid + token + time
        let md5 = md5String(str: combinedString)
        let sign = md5String(str: md5)
        
        //        一定显示声明参数格式是框架提供的格式，否则自动转换格式会使字典为空
        let parameters: Parameters = [
//            "uuid":"\(uuid)"
            "uuid":uuid,
            "sign":sign
        ]
        
        Alamofire.request(url!, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).validate(statusCode: 200..<300).responseJSON { (response) in
            switch response.result{
            case .success:
                if let value = response.result.value {
                    let json = JSON(value)
                    let code = json["code"].stringValue
                    let message = json["message"].stringValue
                    let data = json["data"]
                    print(json)
                    //                print("code:\(code),uid:\(uid),token:\(token),image:\(image),message:\(message),status:\(status)")
                    if(code=="40000"){
                        //                    登录成功：初始化 loginmodel 类型的结构体，保存这些临时参数，返回元组 （true，结构体）
                        
                        let status = json["status"].stringValue
                        let qq = data["qq"].stringValue
                        let user_rank = data["user_rank"].stringValue
                        let uid = data["id"].stringValue
                        let image = data["image"].stringValue
                        let token = data["token"].stringValue
                        let experience = data["experience"].stringValue
                        let birthday = data["birthday"].stringValue
                        let area = data["area"].stringValue
                        let user_name = data["user_name"].stringValue
                        let sex = data["sex"].stringValue
                        gotUserInfo = RequestLoginCode(status: status, code: code, message: message, qq: qq, user_rank: user_rank, userID: uid, imageUrl: image, token: token, experience: experience, birthday: birthday, area: area, user_name: user_name, sex: sex,phoneNumber:"")
                        print("jsondata\(data)")
                        
//                        如果用户更改头像，先修改在本地的 lcode的 imageurl，给”修改字典“传入 key 和 value，在我的页面 willdisappear 时候，根据字典是否为空进行上传操作
//                        if (image != "" && image != lCode?.imageUrl){
//                            AlamofireAsynchronousGETUserHeadImage(headHtml: image, callBack: callBack)
//                        }
                    }
                    else{//有可能是 token 失效，过期等原因，逻辑是应该跳转到登录页面，之后再写吧
                        
                    }
                    
                }
                
            case .failure(let error):
                print(error)
                
            }
        }
    }
    class func AlamofireAsynchronousGETUserHeadImage(headHtml:String,callBack:@escaping (UIImage)->Void) {
        //        下面代码将logo图片下载下来保存到用户文档目录下（Documnets目录）,文件名不变。
        var urlreq = URLRequest(url: URL(string:headHtml)!)
//        if(!headHtml.hasSuffix("http:")){
//            let head = "http://xy.cctvzxjy.com"
//            urlreq = URLRequest(url: URL(string:head)!.appendingPathComponent(headHtml))
//        }
        print(urlreq.url?.absoluteString)
        //        一定显示声明参数格式是框架提供的格式，否则自动转换格式会使字典为空,
        let destination: DownloadRequest . DownloadFileDestination = { _, response in
            let documentsURL = FileManager . default .urls(for: .documentDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent(response.suggestedFilename!)
            //两个参数表示如果有同名文件则会覆盖，如果路径中文件夹不存在则会自动创建
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }

        Alamofire .download(urlreq, to: destination)
            .response { response in
                if let imagePath = response.destinationURL?.path {
                    if let image = UIImage (contentsOfFile: imagePath){
                        currentHeadImage = image
//                        if let data = UIImagePNGRepresentation(image){
//                            let imageName = response.destinationURL?.absoluteString.components(separatedBy: "/").last!
//                            saveImage(imageData:data,imageName:imageName!)
                            callBack(image)
//                    }
                }
        }
                
        
        
    }
    }
//    把以下函数改造成更新用户信息，可以上传图片的方法，问清楚上传图片的接口
    class func AlamofireAsynchronousUpdateUserInfo(key:String,value:String,callBack:@escaping (String)->Void) {
        let urlStr = "http://ad.cctvzxjy.com/User/updateUserInfo"
        let url = URL(string:urlStr)
        let date = Date()
        let time = date.toString("ddmmHH")
        let uuid = (lCode?.userID)!
        let token = (lCode?.token)!
        let combinedString = uuid + token + time
        let md5 = md5String(str: combinedString)
        let sign = md5String(str: md5)
        
        //        一定显示声明参数格式是框架提供的格式，否则自动转换格式会使字典为空
        let parameters: Parameters = [
            //            "uuid":"\(uuid)"
            "uuid":uuid,
            "sign":sign,
            key:value
        ]
        /// - parameter multipartFormData:       The closure used to append body parts to the `MultipartFormData`.
        /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
        ///                                      `multipartFormDataEncodingMemoryThreshold` by default.
        /// - parameter url:                     The URL.
        /// - parameter method:                  The HTTP method. `.post` by default.
        /// - parameter headers:                 The HTTP headers. `nil` by default.
        /// - parameter encodingCompletion:      The closure called when the `MultipartFormData` encoding is complete.

        print(parameters)
        Alamofire.upload(multipartFormData: { (multipartFormData) in
            for (key,value) in parameters{
                multipartFormData.append(((value as! String).data(using: String.Encoding.utf8)!), withName: key)
            }
            
        }, to: url!) { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    if let value = response.result.value as? [String: AnyObject]{
                        let json = JSON(value)
                        print(json)
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
        
    }
    class func AlamofireAsynchronousUploadImage(headImage:UIImage,callBack:@escaping (UIImage)->Void) {
        let urlStr = "http://ad.cctvzxjy.com/User/uploadImage"
        let url = URL(string:urlStr)
        let date = Date()
        let time = date.toString("ddmmHH")
        let uuid = (lCode?.userID)!
        let token = (lCode?.token)!
        let combinedString = uuid + token + time
        let md5 = md5String(str: combinedString)
        let sign = md5String(str: md5)
        let imageKey = "header_img_url"
        
        //        一定显示声明参数格式是框架提供的格式，否则自动转换格式会使字典为空
        let parameters: Parameters = [
            //            "uuid":"\(uuid)"
            "uuid":uuid,
            "sign":sign,
            //            "header_img_url":headImgData//文件流
        ]
//        let data = UIImagePNGRepresentation(headImage)
        let data = UIImageJPEGRepresentation(headImage, 0.5)
        let fileName = "image.png"
        Alamofire.upload(multipartFormData: { (multipartFormData) in
            for (key,value) in parameters{
                multipartFormData.append(((value as! String).data(using: String.Encoding.utf8)!), withName: key)
            }
            multipartFormData.append(data!, withName: imageKey, fileName: fileName, mimeType: "image/png")
        }, to: url!) { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    if let value = response.result.value as? [String: AnyObject]{
                        let json = JSON(value)
                        print(json)
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    }//        uploadFileToHost(urlString: urlStr, name: "header_img_url", fileName: fileName, mimeType: "image/png", paramters: stt, fileData: headImgData as NSData, sucess: { (data) in
//            print(data)
//        }) { (error) in
//            print(error)
//        }
//    }
//        upLoadImageRequest(urlString: urlStr, params: parameters as! [String : String], imageData: headImgData, imageKey: imageKey, imageFileName: fileName, success: { (dic) in
//            print(dic)
//        }) { (error) in
//            print(error)
//        }
//    }
        

        
       
        
        
        
                
                
                
        
    
    class func saveImage(image:UIImage,imageName:String){
        let imageData = UIImagePNGRepresentation(image)
        let imageName = "image.png"
        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
        let filePath = (path as NSString).appendingPathComponent(imageName)
//        print("filePath \(filePath)")
        if let data = imageData{
        NSKeyedArchiver.archiveRootObject(data, toFile: filePath)
        }
    }
    class func loadImage(){
        let fileManager = FileManager.default
        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
        let filePath = (path as NSString).appendingPathComponent("image.png")
        if(fileManager.fileExists(atPath: filePath)){
            let nsdata = NSData(contentsOfFile: filePath)
            if let d = nsdata{
            let data = d as Data
            currentHeadImage = UIImage(data: data)
            }
        }
    }
    class func saveAccount(userInfo:RequestLoginCode)
    {
        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
        let filePath = (path as NSString).appendingPathComponent("userInfo.data")
        print("filePath \(filePath)")
        let user = userInfomation(requestLoginCode: userInfo)
        NSKeyedArchiver.archiveRootObject(user, toFile: filePath)
    }
    
     class func AlamofireAsynchronousGETTimeChartData(stockCode:String, callBack:@escaping (TimeChartResult?)->Void) {
        let url = URL(string:"http://ad.cctvzxjy.com/Index/fenk")
        //        一定显示声明参数格式是框架提供的格式，否则自动转换格式会使字典为空
        let parameters: Parameters = [
            "code":"\(stockCode)"
        ]
        
        //        url：URL 格式的网址；method：post 或者 get 方式等；parameters：请求参数的字典；encoding：以网址方式请求用URLEncoding.default；header：请求头，本次请求没有头部内容
        Alamofire.request(url!, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).validate(statusCode: 200..<300).responseJSON { (response)  in
            switch response.result{
            case .success:
                if let value = response.result.value {
                    let json = JSON(value)
                    let code = json["code"].stringValue
                    var dataArray:[TimeChartData] = []
                    let dataDictionaryArray = json["data"].arrayValue
                    
                    let message = json["message"].stringValue
                    for dataDictionary in dataDictionaryArray{
                        let data = TimeChartData(datetime: dataDictionary["datetime"].stringValue, prevClosePrice: dataDictionary["prevClosePrice"].stringValue, price: dataDictionary["price"].stringValue, volumn: dataDictionary["volumn"].stringValue, volumnPrice: dataDictionary["volumnPrice"].stringValue)
                        dataArray.append(data)
                    }
                    
//                    print(code)
                    if(code == "40000"){
                        //                        登录成功：初始化 loginmodel 类型的结构体，保存这些临时参数，返回元组 （true，结构体）
                        timeChartResult = TimeChartResult(code: code, message: message, data: dataArray)
//                                                print("TimeChartResult:\(timeChartResult!)")
                        callBack(timeChartResult)
//                        NotificationCenter.default.rx.notification(Notification.Name(rawValue: "stockDataGotten"), object: timeChartResult! as AnyObject)
//                        print(code)
                        
                        
                    }
                }
            case .failure(let error):
                print("error")
                
            }
            
        }
    }
    class func AlamofireAsynchronousGETKChartData(stockCode:String, type:KChartType,callBack:@escaping (KChartResult?)->Void) {
        let url = URL(string:"http://ad.cctvzxjy.com/Index/dayk")
        //        一定显示声明参数格式是框架提供的格式，否则自动转换格式会使字典为空
        let parameters: Parameters = [
            "code":"\(stockCode)",
            "time":"\(type.rawValue)"
        ]
        
        //        url：URL 格式的网址；method：post 或者 get 方式等；parameters：请求参数的字典；encoding：以网址方式请求用URLEncoding.default；header：请求头，本次请求没有头部内容
        Alamofire.request(url!, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).validate(statusCode: 200..<300).responseJSON { (response)  in
            switch response.result{
            case .success:
                if let value = response.result.value {
                    let json = JSON(value)
                    let code = json["code"].stringValue
                    var dataArray:[KChartData] = []
                    let dataDictionaryArray = json["data"].arrayValue
                    
                    let message = json["message"].stringValue
                    for dataDictionary in dataDictionaryArray{
                        let data = KChartData(closePrice: dataDictionary["closePrice"].stringValue, code: dataDictionary["code"].stringValue, datetime: dataDictionary["datetime"].stringValue, heightPrice: dataDictionary["heightPrice"].stringValue, lowPrice: dataDictionary["lowPrice"].stringValue, openPrice: dataDictionary["openPrice"].stringValue, volumn: dataDictionary["volumn"].stringValue, avg5: dataDictionary["avg5"].stringValue, avg10: dataDictionary["avg10"].stringValue, avg20: dataDictionary["avg20"].stringValue)
                        dataArray.append(data)
                    }
                    //                    print(code)
                    if(code == "40000"){
                        //                        登录成功：初始化 loginmodel 类型的结构体，保存这些临时参数，返回元组 （true，结构体）
                        let kChartResult = KChartResult(code: code, message: message, data: dataArray)
                        switch type{
                        case .day:
                            dayKChartResult = kChartResult
                        case .week:
                            weekKChartResult = kChartResult
                        case .month:
                            monthKChartResult = kChartResult
                }
                        //                                                print("TimeChartResult:\(timeChartResult!)")
                        callBack(kChartResult)
                        //                        NotificationCenter.default.rx.notification(Notification.Name(rawValue: "stockDataGotten"), object: timeChartResult! as AnyObject)
                        //                        print(code)
                        
                        
                    }
                }
            case .failure(let error):
                print("error")
                
            }
            
        }
    }
    class func AlamofireAsynchronousGETZixuanguData(codes:[String],callBack:@escaping ([ZixuanguData]?)->Void) {
        let url = URL(string:"http://ad.cctvzxjy.com/Index/optional_stock/")//http://ad.cctvzxjy.com/Index/optional_stock/code/000301
        //        一定显示声明参数格式是框架提供的格式，否则自动转换格式会使字典为空
        var mutipleCodeComma = ""
        for code in codes{
            mutipleCodeComma = mutipleCodeComma+code+","
        }
        let mutipleCode = mutipleCodeComma.dropLast()
        let parameters: Parameters = [
            "code":mutipleCode
        ]
        
        //        url：URL 格式的网址；method：post 或者 get 方式等；parameters：请求参数的字典；encoding：以网址方式请求用URLEncoding.default；header：请求头，本次请求没有头部内容
        Alamofire.request(url!, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).validate(statusCode: 200..<300).responseJSON { (response)  in
            switch response.result{
            case .success:
                if let value = response.result.value {
                    let json = JSON(value)
                    let code = json["code"].stringValue
                    let dataDictionaryArray = json["data"].arrayValue
                    let message = json["message"].stringValue
                    var dataArray:[ZixuanguData] = []
                    for dataDictionary in dataDictionaryArray{
                    let data = ZixuanguData(name: dataDictionary["name"].stringValue, code: dataDictionary["code"].stringValue, nowPrice: dataDictionary["nowPrice"].stringValue, diff_rate: dataDictionary["diff_rate"].stringValue)
                         dataArray.append(data)
                    }
                    //                    print(code)
                    if(code == "40000"){
                        //                        登录成功：初始化 loginmodel 类型的结构体，保存这些临时参数，返回元组 （true，结构体）
//                                               print("TimeChartResult:\(timeChartResult!)")
                        zixuanguResult=ZixuanguResult(code: code, message: message, data: dataArray)
                        callBack(dataArray)
                        //                        NotificationCenter.default.rx.notification(Notification.Name(rawValue: "stockDataGotten"), object: timeChartResult! as AnyObject)
                        //                        print(code)
                        
                        
                    }
                }
                
            case .failure(let error):
                print("error")
            }
            
        }
        
    }
    class func calculateMA(type:Int,index:Int,array:[KChartData],currentElement:HSKLineModel)->CGFloat{
        if (index<type-1){
            return currentElement.close
        }else{
            var sum = 0.0
            for i in (index-type+1)...index{
                sum = sum + Double(array[i].closePrice)!
            }
            return CGFloat(sum/Double(type))
        }
    }
    class func AlamofireAsynchronousGETZixuanguMarketData(callBack:@escaping ([ZixuanguMarketData]?)->Void) {
        let url = URL(string:"http://ad.cctvzxjy.com/Index/Index")//http://ad.cctvzxjy.com/Index/optional_stock/code/000301
        //        一定显示声明参数格式是框架提供的格式，否则自动转换格式会使字典为空
        //        url：URL 格式的网址；method：post 或者 get 方式等；parameters：请求参数的字典；encoding：以网址方式请求用URLEncoding.default；header：请求头，本次请求没有头部内容
        Alamofire.request(url!, method: .get, parameters: [:], encoding: URLEncoding.default, headers: nil).validate(statusCode: 200..<300).responseJSON { (response)  in
            switch response.result{
            case .success:
                if let value = response.result.value {
                    let json = JSON(value)
                    let code = json["code"].stringValue
                    let message = json["message"].stringValue
                    if(code == "40000"){
                    let dataDictionaryArray = json["data"].arrayValue
                    var dataArray:[ZixuanguMarketData] = []
                    for dataDictionary in dataDictionaryArray{
                        let data = ZixuanguMarketData(yestodayClosePrice: dataDictionary["yestodayClosePrice"].stringValue, todayMax: dataDictionary["todayMax"].stringValue, todayMin: dataDictionary["todayMin"].stringValue, max52: dataDictionary["max52"].stringValue, diff_money: dataDictionary["diff_money"].stringValue, tradeNum: dataDictionary["tradeNum"].stringValue, code: dataDictionary["code"].stringValue, maxPrice: dataDictionary["maxPrice"].stringValue, nowPrice: dataDictionary["nowPrice"].stringValue, min52: dataDictionary["min52"].stringValue, time: dataDictionary["time"].stringValue, market: dataDictionary["market"].stringValue, name: dataDictionary["name"].stringValue, tradeAmount: dataDictionary["tradeAmount"].stringValue, swing: dataDictionary["swing"].stringValue, todayOpenPrice: dataDictionary["todayOpenPrice"].stringValue, diff_rate: dataDictionary["diff_rate"].stringValue, minPrice: dataDictionary["minPrice"].stringValue)
                        dataArray.append(data)
                    }
                        print(json)
                        callBack(dataArray)
                    }
                }
            case .failure(let error):
                
                print("error")
                
            }
        }
    }
    class func AlamofireAsynchronousGETStockDetailData(code:String,callBack:@escaping (StockDetailData?)->Void) {
        let url = URL(string:"http://ad.cctvzxjy.com/Index/detail/")//http://ad.cctvzxjy.com/Index/search/code/000301
        //        一定显示声明参数格式是框架提供的格式，否则自动转换格式会使字典为空
        let parameters : Parameters = [
            "code":code
        ]
        //        url：URL 格式的网址；method：post 或者 get 方式等；parameters：请求参数的字典；encoding：以网址方式请求用URLEncoding.default；header：请求头，本次请求没有头部内容
        Alamofire.request(url!, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).validate(statusCode: 200..<300).responseJSON { (response)  in
            switch response.result{
            case .success:
                if let value = response.result.value {
                    let json = JSON(value)
                    let code = json["code"].stringValue
                    let message = json["message"].stringValue
                    if(code == "40000"){
                        let data = json["data"]
                        
                        print(data["volumn"])
                        let stockDetailData = StockDetailData(totalValue: data["totalValue"].stringValue, code: data["code"].stringValue, change: data["change"].stringValue, volumnPrice: data["volumnPrice"].stringValue, volumn: data["volumn"].stringValue, type: data["type"].stringValue, peRatio: data["peRatio"].stringValue, lowPrice: data["lowPrice"].stringValue, price: data["price"].stringValue, name: data["name"].stringValue, turnoverRate: data["turnoverRate"].stringValue, highPrice: data["highPrice"].stringValue, closePrice: data["closePrice"].stringValue, openPrice: data["openPrice"].stringValue, totalShares: data["totalShares"].stringValue, dateTime: data["dateTime"].stringValue, changePct: data["changePct"].stringValue, swing: data["swing"].stringValue, cityNetRate: data["cityNetRate"].stringValue, circulationValue: data["circulationValue"].stringValue)
                        callBack(stockDetailData)
                    }else{
                    }
                }
                
            case .failure(let error):
                print("error")
                
            }
            
        }
        
    }
    class func saveCodes(){
        let array = collectedCodes as NSArray
        let filePath: String = NSHomeDirectory () + "/Documents/collectedCodes.plist"
       array.write(toFile: filePath, atomically: true)
    }
    class func loadCodes(){
        let fileManager = FileManager.default
        let filePath = NSHomeDirectory () + "/Documents/collectedCodes.plist"
        if(fileManager.fileExists(atPath: filePath)){
        let array = NSArray(contentsOfFile: filePath)
        collectedCodes = array as! [String]
        }else{
            collectedCodes = []
        }
    }
//    class func synchronousPost(pNumber:String,verificationCode:String)  {
//        print("test")
//        // 1、创建URL对象；
//        let url:URL! = URL(string:"http://ad.cctvzxjy.com/User/login");
//
//        // 2、创建Request对象
//        // url: 请求路径
//        // cachePolicy: 缓存协议
//        // timeoutInterval: 网络请求超时时间(单位：秒)
//        var urlRequest:URLRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
//
//        // 3、设置请求方式为POST，默认是GET
//        urlRequest.httpMethod = "POST"
//
//        // 4、设置参数
//        let str:String = "mobile=\(pNumber)&code=\(verificationCode)"
//        let data:Data = str.data(using: .utf8, allowLossyConversion: true)!
//        urlRequest.httpBody = data;
//
//        // 5、响应对象
//        var response:URLResponse?
//
//        // 6、发出请求
//        do {
//
//            let received =  try NSURLConnection.sendSynchronousRequest(urlRequest, returning: &response)
//            let dic = try JSONSerialization.jsonObject(with: received, options: JSONSerialization.ReadingOptions.allowFragments)
//            print(dic)
////            let requestLoginResult = requestLoginCode(dictionary: dic as! Dictionary<String, Any>)
////            print(requestLoginResult)
//
//
//            //switch-case 这个 code，为40000时成功
//
//
//
//            //let jsonStr = String(data: received, encoding:String.Encoding.utf8);
////            print(jsonStr)
//
//        } catch let error{
//            print(error.localizedDescription);
//        }
//    }
}
//        Alamofire.request(.POST, url, parameters:dic , encoding: ParameterEncoding.JSON, headers: headers).responseJSON{ (response)  in



